<script setup lang="ts">
import { Checkbox, CheckboxGroup } from "vant";
import { ref, watch } from "vue";
import checkall from "./images/allChecked.png";
import checkhalf from "./images/halfChecked.png";
import checkno from "./images/noCheck.png";
import { computed } from "vue";

// 复选数据格式
type dataInfo = {
	key: string | number;
	name: string;
};

// 父组件传参
const propsData = withDefaults(
	defineProps<{
		modelValue: any[]; // 选中值
		checkedDatas: Array<dataInfo>; // 多选时的选项
		label?: string; // 全选半选的文本显示
	}>(),
	{
		label: "全选", // 默认全选
	}
);

const emits = defineEmits<{
	(e: "update:modelValue", val: any[]): void;
}>();

// 已勾选的值
const groupChecked = ref<any[]>([]);

// 组内单选
const checkboxChange = function (names: any[]) {
	console.log(names);
};

// 全选半选
const groupCheckChange = function () {
	if (groupChecked.value.length < propsData.checkedDatas.length) {
		propsData.checkedDatas.forEach((x: dataInfo) => {
			if (groupChecked.value.indexOf(x.key) === -1) {
				groupChecked.value.push(x.key);
			}
		});
	} else {
		groupChecked.value.length = 0;
	}
};

// 全选半选样式值
const getCheckImg = computed(() => {
	if (groupChecked.value.length === propsData.checkedDatas.length) {
		return checkall;
	} else if (
		groupChecked.value.length > 0 &&
		groupChecked.value.length < propsData.checkedDatas.length
	) {
		return checkhalf;
	} else {
		return checkno;
	}
});

watch(groupChecked, (newVal: any[]) => {
	emits("update:modelValue", newVal);
});
</script>
<template>
	<div class="container">
		<checkbox @click="groupCheckChange">
			{{ propsData.label }}
			<template #icon>
				<img class="img-icon" :src="getCheckImg" />
			</template>
		</checkbox>
		<checkbox-group v-model="groupChecked" ref="checkboxGroup" @change="checkboxChange">
			<checkbox v-for="item in propsData.checkedDatas" :key="item.key" :name="item.key">
				{{ item.name }}
			</checkbox>
		</checkbox-group>
	</div>
</template>

<style lang="scss" scoped>
.img-icon {
	width: 21px;
	height: 21px;
}
.van-checkbox {
	height: 48px;
	line-height: 48px;
	border-bottom: 1px solid #eeeeee;
}
</style>
